package com.cxd.app.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cxd.app.entity.base.SourceReferrerBase;
import com.cxd.app.entity.base.TrusteeshipAccountBase;
import com.cxd.app.entity.base.TrusteeshipOperationBase;
import com.cxd.app.entity.base.UserActivityBase;
import com.cxd.app.entity.base.UserBase;
import com.cxd.app.entity.base.UserMessageTemplateBase;
import com.cxd.app.entity.base.UserRoleBase;
import com.cxd.app.entity.base.UserTokenBase;
import com.cxd.app.mapper.read.RInvestMapper;
import com.cxd.app.mapper.read.RLoanMapper;
import com.cxd.app.mapper.write.WUserActivityMapper;
import com.cxd.app.service.tools.AppYeePay;
import com.cxd.app.service.tools.YeePayParams;
import com.cxd.base.common.constants.CommonConstants;
import com.cxd.base.common.constants.MessageConstants;
import com.cxd.base.common.constants.UserConstants;
import com.cxd.base.common.constants.YeePayConstants;
import com.cxd.base.common.constants.role.RoleConstants;
import com.cxd.base.common.exception.AuthInfoAlreadyActivedException;
import com.cxd.base.common.exception.AuthInfoOutOfDateException;
import com.cxd.base.common.exception.CxdException;
import com.cxd.base.common.exception.ExceptionEnum;
import com.cxd.base.common.exception.NoMatchingObjectsException;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.HashCrypt;
import com.cxd.base.util.HtmlElementUtil;
import com.cxd.base.util.IdCardUtil;
import com.cxd.base.util.IdGenerator;
import com.cxd.base.util.MapUtil;
import com.cxd.base.util.ParamUtil;
import com.cxd.base.util.date.DateStyle;
import com.cxd.base.util.date.DateUtil;
import com.cxd.base.util.wtj.BUtils;
import com.cxd.message.exception.AppConstants;
import com.cxd.message.exception.CFCASignUtil;
import com.cxd.message.exception.TrusteeshipConstants;
import com.cxd.sms.service.SmsService;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2015年12月1日 下午6:49:39
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
@Service("userService")
public class UserService {
	public static final String USER_MEETING = "METTING_2016_06";
	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(UserService.class);
	
	@Resource
	public BeanTools bt;
	
	@Resource
	UserService userService;
	
	@Resource
	public AuthService authService;
	
	@Resource
	public SmsService smsService;
	
	@Resource
	public DictService dictService;
	
	@Resource
	public RInvestMapper rinvestMapper;
	
	@Resource
	public LoanService loanService;
	
	@Resource
	public RLoanMapper rloanMapper;
	
	@Resource
	private WUserActivityMapper wuserActivityMapper;
	
	@Resource
	public TrusteeshipOperationService trusteeshipOperationService;
	
	@Resource
	public BeanService beanService;
	/**
	 * 用户登录
	 * @author wtj
	 * @date 2015年12月8日上午11:23:17
	 * @param json
	 * @param value
	 */
	public void toLogin(JSONObject json, String value){
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object loginName = param.get("loginName");
		Object psw = param.get("password");
		ParamUtil.notNullParam("登录名:"+loginName,"密码不能:"+psw);
		this.toLogin(json, loginName.toString(), psw.toString());
	}
	public void toLogin(JSONObject json, String loginName,String psw){
		String ln = loginName.toString().trim();
		String sql = "SELECT * FROM USER WHERE (USERNAME='"+ln+"' OR EMAIL='"+ln+"' ) and password='"+HashCrypt.getDigestHash(psw.toString())+"'";
		List<UserBase> listBean = bt.queryListBean(sql, UserBase.class);
		
		if(listBean == null || listBean.size()==0){
			sql = "SELECT * FROM USER WHERE (MOBILE_NUMBER='"+ln+"') and password='"+HashCrypt.getDigestHash(psw.toString())+"'";
			listBean = bt.queryListBean(sql, UserBase.class);
		}
		
		if(listBean == null||listBean.size()==0||listBean.size()>1){
			json.put("status", 500);
			json.put("msg", "用户名不存在或者用户名和密码不符");
			json.put("result",new String[]{});
		}else{
			if(listBean.size() ==1){
				UserBase user = listBean.get(0);
				if(user.getIdentityType().equals(UserConstants.IdentityType.COMPANY)){
					json.put("status", 500);
					json.put("msg", "企业账户不允许登录APP");
					json.put("result",new String[]{});
				}else{
					user.setSex(dictService.getValue("user_sex",user.getSex()));
					Map<String,Object> resultMap = BUtils.beanToMap(user);
					resultMap.put("token", loadUserToken(user.getId()));
					json.put("result",resultMap);
					json.put("status", 200);
					json.put("msg", "登录成功");
				}
			}
		}
	}
	
	/**
	 * 获取用户登录TOKEN
	 * @author wtj
	 * @date 2015年12月9日下午2:10:45
	 * @param userId
	 * @return
	 */
	public String loadUserToken(String userId){
		UserTokenBase utBean = bt.queryBean("USER_TOKEN", "ID", userId, UserTokenBase.class);
		if(utBean==null){
			utBean = new UserTokenBase();
			utBean.setId(userId);
			utBean.setCtime(new Date());
			utBean.setToken(IdGenerator.randomUUID());
			bt.add(utBean);
		}else{
			utBean.setCtime(new Date());
			utBean.setToken(IdGenerator.randomUUID());
			bt.modify(utBean);
		}
		return utBean.getToken();
	}
	/**
	 * 用户注册
	 * @author wtj
	 * @date 2015年12月8日上午11:23:49
	 * @param value
	 */
	@Transactional
	public void register(HttpServletRequest request,JSONObject json,String value){
		try {
			Map<String,String> param = MapUtil.jsonToMapString(value);
			String mobileNumber=param.get("phoneNo");//手机号,必填
			int countNum = bt.queryForInt("select count(0) countNum from user where mobile_number='"+mobileNumber+"' or username ='"+mobileNumber+"'");
			if(countNum>0){
				json.clear();
				throw new CxdException("手机已经存在");
			}
			
			String username=param.get("userName");//用户名,必填
			String password=param.get("password");//密码,必填
			//	String email=param.get("email");//邮箱,必填
			String authCode=param.get("authCode");//验证码，必填
			String sourceType=param.get("sourceType");//验证码，必填
			String sourceCode=param.get("sourceCode");//验证码，必填
			int userNum = bt.queryForInt("select count(0) countNum from user where id='"+username+"' or username='"+username+"'");
			if(userNum > 0){
				json.clear();
				throw new CxdException("用户已经存在");
			}
			
			if(StringUtils.isBlank(username) 
					|| StringUtils.isBlank(password)
					//	|| StringUtils.isBlank(email)
					|| StringUtils.isBlank(mobileNumber)
					|| StringUtils.isBlank(authCode)){
				throw new CxdException("数据不完整,请检查");
			}
			String referrer=param.get("referrer").trim();//推荐人
			String referrerUserid = null;
			if(StringUtils.isNotBlank(referrer) && referrer!=""){
				//判断推荐人是否存在
				UserBase userBase = userService.getUserByMobile(referrer);
				if(null == userBase || null == userBase.getId()){
					throw new CxdException("推荐人不存在");
				}
				referrerUserid = userBase.getId();
			}

			if(StringUtils.isBlank(sourceCode)){
				sourceCode = request.getHeader("sourceCode"); //官网code
			}
			
			if(StringUtils.isBlank(sourceType)){
				sourceType = request.getHeader("sourceType"); //移动端统称  渠道终端类型  1:and 2:ios
			}
			
			if(StringUtils.isBlank(sourceType)){
				sourceType = "3";
			}
			String useVersion = request.getHeader("useVersion");// 使用版本
			if(StringUtils.isBlank(useVersion)){
				useVersion = "1.0.0";
			}
			String sourceName = "";
			if(StringUtils.isBlank(sourceCode)){
				sourceCode = "cc044b21bfba95aed0cfa42393db9dcf424e587b";
				sourceName = "诚信贷";
			}else{
				SourceReferrerBase srBean = bt.queryBean("SOURCE_REFERRER", "SOURCE_CODE", sourceCode, SourceReferrerBase.class);
				if(srBean != null){
					sourceName=srBean.getSourceName();
				}
			}
			UserBase user = new UserBase();
			user.setId(username);
			user.setUsername(username);
			//	user.setEmail(email);
			user.setPassword(password);
			user.setMobileNumber(mobileNumber);
			user.setReferrer(referrerUserid);
			
			user.setSourceName(sourceName);
			user.setSourceType(sourceType);
			user.setUseVersion(useVersion);
			
			//验证手机认证码是否正确
			if(CommonConstants.isTest){
				authService.verifyAuthInfo(null, user.getMobileNumber(), authCode,
						CommonConstants.AuthInfoType.REGISTER_BY_MOBILE_NUMBER);
			}

			user.setRegisterTime(new Date());
			//用户密码通过sha加密
			user.setPassword(HashCrypt.getDigestHash(user.getPassword()));
			user.setCashPassword(HashCrypt.getDigestHash(user.getCashPassword()));
			user.setStatus(UserConstants.UserStatus.ENABLE);
			bt.add(user);
			
			// 添加普通用户权限
			UserRoleBase userRole = new UserRoleBase();
			userRole.setRoleId(RoleConstants.MEMBER);
			userRole.setUserId(user.getId());
			bt.add(userRole);
			List<UserBase> userList = new ArrayList<UserBase>();
			userList.add(user);
			json.clear();
			json.put("result",userList);
		} catch (JSONException e) {
			throw new CxdException(ExceptionEnum.JSONException.getExceDes());
		}catch (NoMatchingObjectsException e) {
			throw new CxdException("验证码有误请核对后重新输入");
		} catch (AuthInfoOutOfDateException e) {
			throw new CxdException(ExceptionEnum.AuthInfoOutOfDateException.getExceDes());
		} catch (AuthInfoAlreadyActivedException e) {
			throw new CxdException(ExceptionEnum.AuthInfoAlreadyActivedException.getExceDes());
		} catch (InstantiationException e) {
			throw new CxdException(ExceptionEnum.InstantiationException.getExceDes());
		} catch (IllegalAccessException e) {
			throw new CxdException(ExceptionEnum.IllegalAccessException.getExceDes());
		} 
	}
	
	// 注册手机 给手机发送验证码
	public JSONObject verifyAuthInfo(JSONObject json,String mobileNumber) throws InstantiationException, IllegalAccessException{
		// FIXME:验证手机号码的合法性
		// 发送手机验证码
		Map<String, String> params = new HashMap<String, String>();
		// TODO:实现模板
		params.put("time", DateUtil.dateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM_SS_CN.getValue()));
		params.put("authCode",
				authService.createAuthInfo(null, mobileNumber, null,
						CommonConstants.AuthInfoType.REGISTER_BY_MOBILE_NUMBER)
						.getAuthCode());
		UserMessageTemplateBase umtb = bt.queryBean("USER_MESSAGE_TEMPLATE", "ID", MessageConstants.UserMessageNodeId.REGISTER_BY_MOBILE_NUMBER+ "_sms", UserMessageTemplateBase.class);
		smsService.sendSMS(umtb, params, mobileNumber);
		json.put("result", params);
		return json;
	}
	
	/**
	 * 获取用户信息
	 * @author wtj
	 * @date 2015年12月8日下午3:21:03
	 * @param json
	 * @param value
	 */
	public void userInfo(JSONObject json, String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		ParamUtil.notNullParam("用户名:"+userId);
		UserBase user = beanService.getUserById(userId);
		if(user != null ){
			user.setSex(dictService.getValue("user_sex",user.getSex()));
			json.put("result",user);
			json.put("status", 200);
			json.put("msg", "获取成功");
		}else{
			json.put("status", 500);
			json.put("msg", "用户不存在");
		}
	}
	/**
	 * 实名认证
	 * @author wtj
	 * @date 2015年12月8日下午7:04:08
	 * @param json
	 * @param value
	 */
	@Transactional
	public void realnameAuthentication(JSONObject json, String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		String realName =  param.get("realName");
		String idCardNo =  param.get("idCard").trim().toLowerCase();
		String phoneNo =  param.get("phoneNo");
		String email =  param.get("email");
		ParamUtil.notNullParam("用户名:"+userId,"真实姓名:"+realName,"身份证号:"+idCardNo,"手机号:"+phoneNo);
		String sex=IdCardUtil.getSex(idCardNo);
		Date birthday;
		try {
			birthday = IdCardUtil.getDate(idCardNo);
		} catch (ParseException e) {
			throw new CxdException("身份证号码有误");
		}
		if(noCheckIdCard(idCardNo)){
			UserBase idCardUser  = bt.queryBean("user", "id_card", idCardNo, UserBase.class);
			if(idCardUser!=null){
				/**
				 * 流程造成的垃圾数据，user存在用户的身份证、真实姓名信息
				 * 但TRUSTEESHIP_ACCOUNT没有用户认证信息，所以可以重新认证
				 */
				TrusteeshipAccountBase bean = bt.queryBean("TRUSTEESHIP_ACCOUNT", "ID", userId, TrusteeshipAccountBase.class);
				if(bean!=null){
					throw new CxdException("身份证号为"+idCardNo+"的用户用户已经存在,如有疑问请联系管理员");
				}
			}
		}
		UserBase user = beanService.getUserById(userId);
			user.setRealname(realName);
			user.setIdCard(idCardNo);
			user.setMobileNumber(phoneNo);
			user.setEmail(email);
			user.setSex(sex);
			user.setBirthday(birthday);
			bt.modify(user);
		String reqContent = YeePayParams.realnameAuthenticationParams(user);
		Map<String, String> params = new HashMap<String, String>();
		params.put("req", reqContent);
		String sign = CFCASignUtil.sign(reqContent);
		params.put("sign", sign);
		TrusteeshipOperationBase to = new TrusteeshipOperationBase();
			to.setId(IdGenerator.randomUUID());
			to.setMarkId(userId);
			to.setOperator(userId);
			to.setRequestTime(new Date());
			to.setRequestUrl(AppConstants.RequestUrl.APP_AUTHENTICATION_URL);
			
			String requestData = HtmlElementUtil.createAutoSubmitForm(params,AppConstants.RequestUrl.APP_AUTHENTICATION_URL,"UTF-8");
			
			to.setRequestData(requestData);
			to.setStatus(TrusteeshipConstants.Status.SENDED);
			to.setType(YeePayConstants.OperationType.CREATE_ACCOUNT);
			to.setTrusteeship("yeepay");
			trusteeshipOperationService.save(to);
		Map<String,Object> mapHtml = new HashMap<String,Object>();
		mapHtml.put("sign", sign);
		mapHtml.put("isIntercept", "false");
		mapHtml.put("reqContent", reqContent);//StringEscapeUtils.escapeHtml(reqContent));
		mapHtml.put("actionUrl", AppConstants.RequestUrl.APP_AUTHENTICATION_URL);
		mapHtml.put("callbackUrl", 	AppConstants.ResponseWebUrl.PRE_RESPONSE_URL+ YeePayConstants.OperationType.CREATE_ACCOUNT );
		json.put("result", mapHtml);
	}
	
	/**
	 * 重置密码
	 * @author wtj
	 * @date 2015年12月8日下午7:15:01
	 * @param json
	 * @param value
	 */
	public JSONObject resetPsw(JSONObject json,String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String authCode = param.get("authCode");
		String password = param.get("password");
		String phoneNo = param.get("phoneNo");
//		String userName = param.get("userName");
		ParamUtil.notNullParam("验证码:"+authCode,"密码:"+password,"手机号:"+phoneNo);
		//--------------------------------------------------------------------
		//1.获取手机验证码(调用authCodeService)
		//2.核对手机验证码是否正确
		//3.修改密码
		//--------------------------------------------------------------------
		UserBase user = bt.queryBean("USER", new String[]{"MOBILE_NUMBER"}, new String[]{phoneNo.trim()}, UserBase.class);
		if(user == null){
			json.put("status", 500);
			json.put("msg", "用户名或手机错误");
			return json;
		}else{
			//验证手机认证码是否正确
			try{
				authService.verifyAuthInfo(null, user.getMobileNumber(), authCode,
						CommonConstants.AuthInfoType.REGISTER_BY_MOBILE_NUMBER);
				UserBase u = new UserBase();
				u.setId(user.getId());
				u.setPassword(HashCrypt.getDigestHash(password));
				u.setCashPassword(HashCrypt.getDigestHash(password));
				bt.modify(u);
				json.put("result", new String[]{});
				return json;
			} catch (JSONException e) {
				throw new CxdException(ExceptionEnum.JSONException.getExceDes());
			} catch (NoMatchingObjectsException e) {
				throw new CxdException("验证码有误请核对后重新输入");
			} catch (AuthInfoOutOfDateException e) {
				throw new CxdException(ExceptionEnum.AuthInfoOutOfDateException.getExceDes());
			} catch (AuthInfoAlreadyActivedException e) {
				throw new CxdException(ExceptionEnum.AuthInfoAlreadyActivedException.getExceDes());
			} catch (InstantiationException e) {
				throw new CxdException(ExceptionEnum.InstantiationException.getExceDes());
			} catch (IllegalAccessException e) {
				throw new CxdException(ExceptionEnum.IllegalAccessException.getExceDes());
			} 
		}
	}
	
	/**
	 * 修改密码
	 * @author wtj
	 * @date 2015年12月23日下午10:00:56
	 * @param json
	 * @param value
	 */
	public JSONObject updatePsw(JSONObject json,String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		String oldPsw = param.get("oldPsw");
		String newPsw = param.get("newPsw");
		ParamUtil.notNullParam("用户名:"+userId,"原密码:"+oldPsw,"新密码:"+newPsw);
		UserBase userBase = bt.queryBean("user", "id", userId, UserBase.class);
		if(userBase==null){
			json.put("status", 500);
			json.put("msg", "没有找到用户信息");
			return json;
		}
		if(!userBase.getPassword().equals(HashCrypt.getDigestHash(oldPsw))){
			json.put("status", 500);
			json.put("msg", "原密码错误");
			
			return json;
		}
		UserBase user = new UserBase();
		user.setId(userId);
		user.setPassword(HashCrypt.getDigestHash(newPsw));
		bt.modify(user);
		json.put("result", new String[]{});
		return json;
	}
	
	
	/**
	 * 权限验证
	 * <一句话功能简述> <功能详细描述>
	 * @author wtj
	 * @date 2015年12月18日下午3:59:45
	 * @param request
	 * @return
	 */
	public boolean checkToken(HttpServletRequest request){
		Object  token = request.getHeader("TOKEN");
		if(token==null){
			return false;
		}
		UserTokenBase utBean = bt.queryBean("USER_TOKEN", "token", token.toString(), UserTokenBase.class);
		if(utBean==null){
			return false;
		}else{
			return true;
		}
	}
	/**
	 * <一句话功能简述> <功能详细描述>
	 * @author wtj
	 * @date 2016年4月25日下午2:20:57
	 * @param token
	 * @return
	 */
	public boolean checkToken(Object token){
		if(token==null){
			return false;
		}
		UserTokenBase utBean = bt.queryBean("USER_TOKEN", "token", token.toString(), UserTokenBase.class);
		if(utBean==null){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * 判断用户名称是否可以使用
	 * @author wtj
	 * @date 2015年12月18日下午4:09:13
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject isUseUserName(JSONObject json,String value){
		Map<String,String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		ParamUtil.notNullParam("用户名:"+userId);
		int countNum = bt.queryForInt("select count(0) countNum from user where id='"+userId+"' or username='"+userId+"'");
		
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		if(countNum == 0){
			json.put("msg","用户不存在，可以使用");
			jsonMap.put("isUse", "true");
		}else{
			json.put("msg","用户已经存在");
			jsonMap.put("isUse", "false");
		}
		json.put("result", jsonMap);
		return json;
	}
	
	/**
	 * 重置易宝交易密码
	 * @author wtj
	 * @date 2015年12月23日下午10:46:13
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject resetYeePayPsw(JSONObject json,String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		ParamUtil.notNullParam("用户名:"+userId);
		UserBase user = beanService.getUserById(userId);
		if(user==null){
			json.put("status", 500);
			json.put("msg", "用户不存在");
			return json;
		}
		
		AppYeePay p = new AppYeePay();
			p.setActionUrl(AppConstants.RequestUrl.APP_RESET_PASSWORD_URL);
			p.setCallbackUrl(AppConstants.ResponseWebUrl.PRE_RESPONSE_URL+YeePayConstants.OperationType.RESET_PASSWORD);
			p.setRequestNo(YeePayConstants.RequestNoPre.RESET_YEEPAY_PSW);
			
		String reqContent = YeePayParams.resetYeePayPsw(user,p);
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("req", reqContent);
		String sign = CFCASignUtil.sign(reqContent);
		params.put("sign", sign);
		TrusteeshipOperationBase to = new TrusteeshipOperationBase();
			to.setId(IdGenerator.randomUUID());
			to.setMarkId(userId);
			to.setOperator(userId);
			to.setRequestTime(new Date());
			to.setRequestUrl(p.getActionUrl());
			to.setRequestData(MapUtil.mapToString(params));
			to.setStatus(TrusteeshipConstants.Status.SENDED);
			to.setType(YeePayConstants.OperationType.RESET_PASSWORD);
			to.setTrusteeship("yeepay");
			trusteeshipOperationService.save(to);
		Map<String,Object> mapHtml = new HashMap<String,Object>();
		mapHtml.put("sign", sign);
		mapHtml.put("isIntercept", "false");
		mapHtml.put("reqContent", reqContent);//StringEscapeUtils.escapeHtml()
		mapHtml.put("actionUrl", p.getActionUrl());
		mapHtml.put("callbackUrl", 	p.getCallbackUrl() );
		json.put("result", mapHtml);
		return json;
	}
	
	/**
	 * 修改易宝手机号
	 * @author wtj
	 * @date 2015年12月26日下午10:46:13
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject resetYeePayMobile(JSONObject json,String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		ParamUtil.notNullParam("用户名:"+userId);
		UserBase user = beanService.getUserById(userId);
		if(user==null){
			json.put("status", 500);
			json.put("msg", "用户不存在");
			return json;
		}
		
		AppYeePay p = new AppYeePay();
		p.setActionUrl(AppConstants.RequestUrl.APP_RESET_MOBILE_URL);
		p.setCallbackUrl(AppConstants.ResponseWebUrl.PRE_RESPONSE_URL+YeePayConstants.OperationType.RESET_MOBILE);
		p.setNotifyUrl(AppConstants.ResponseS2SUrl.PRE_RESPONSE_URL+ YeePayConstants.OperationType.RESET_MOBILE);
		p.setRequestNo(YeePayConstants.RequestNoPre.RESET_YEEPAY_MOBILE);
			
		String reqContent = YeePayParams.resetYeePayMobile(user,p);
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("req", reqContent);
		String sign = CFCASignUtil.sign(reqContent);
		params.put("sign", sign);
		
		TrusteeshipOperationBase to = new TrusteeshipOperationBase();
		to.setId(IdGenerator.randomUUID());
		to.setMarkId(userId);
		to.setOperator(userId);
		to.setRequestTime(new Date());
		to.setRequestUrl(p.getActionUrl());
		to.setRequestData(MapUtil.mapToString(params));
		to.setStatus(TrusteeshipConstants.Status.SENDED);
		to.setType(YeePayConstants.OperationType.RESET_MOBILE);
		to.setTrusteeship("yeepay");
		trusteeshipOperationService.save(to);
		
		Map<String,Object> mapHtml = new HashMap<String,Object>();
		mapHtml.put("sign", sign);
		mapHtml.put("isIntercept", "true");
		mapHtml.put("reqContent", reqContent);
		mapHtml.put("actionUrl", p.getActionUrl());
		mapHtml.put("callbackUrl", 	p.getCallbackUrl() );
		json.put("result", mapHtml);
		return json;
	}

	public UserBase getUserByMobile(String mobile) {
		String sql = "select * from user where mobile_number = '"+mobile+"'";
		return bt.queryBean(sql, UserBase.class);
	}

	/**
	 * 根据被推荐人手机号，获取被推荐人List
	 * @param mobileNumber
	 * @return
	 */
	public List<UserBase> getReferrerListByUserId(String userId) {
		String sql = "select * from user where referrer = '"+userId+"'";
		return bt.queryListBean(sql, UserBase.class);
	}
	/**
	 * 获取用户待收金额（去除诚信贷理财计划8天标
	 * @param userId
	 * @return
	 */
	public Double getUserSumInvestNo8Day(String userId) {
		return rinvestMapper.getUserSumInvestNo8Day(userId);
	}

	/**
	 * 保存用户活动报名信息
	 * @param mobile
	 * @param user
	 * @return
	 */
	public int saveActivityApply(String mobile,UserBase user,Double investMoney,String status) {
		UserActivityBase userActivity = new UserActivityBase();
		userActivity.setApplyTime(new Date());
		userActivity.setId(IdGenerator.randomUUID());
		userActivity.setMobile(mobile);
		userActivity.setUserId(user.getId());
		userActivity.setRealname(user.getRealname());
		userActivity.setType(UserService.USER_MEETING);
		userActivity.setStatus(status);
		userActivity.setInvestMoney(investMoney+"");
		return wuserActivityMapper.insertSelective(userActivity);
	}

	/**
	 * 获取用户投资回款日历
	 * @author wtj
	 * @date 2016年5月11日下午3:54:07
	 * @param json
	 * @param valuse
	 * @return
	 */
	public void loanInvestBackCalendar(JSONObject json,String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		String backDate = param.get("backDate");
		ParamUtil.notNullParam("用户ID:"+userId,"回款月份:"+backDate);
		String sql = "select ir.repay_day as dayStr  from invest inv INNER JOIN invest_repay ir on inv.id = ir.invest_id where inv.user_id = '%s' and ir.`status` = 'repaying' and LEFT(ir.repay_day,7) = '%s'";
		List<Map<String,Object>> bcList = bt.queryListMap(String.format(sql, userId,backDate));
		if(bcList==null){
			json.put("result", "{dateList:''}");
		}else{
			Set<Object> cList = new HashSet<Object>();
			for(Map<String,Object> m:bcList){
				cList.add(DateUtil.stringToString(m.get("dayStr").toString(),DateStyle.YYYY_MM_DD.getValue()));
			}
			Map<String,Object> dlMap = new HashMap<String,Object>();
			dlMap.put("dateList", cList);
			json.put("result",dlMap);
		}
	}
	/**
	 * 根据手机号查询用户活动报名情况
	 * @param mobile
	 * @return
	 */
	public UserActivityBase getActivityApplyOldByMobile(String mobile) {
		String sql = "select * from user_activity where mobile='"+mobile+"' and type!='%s'";
		return bt.queryBean(String.format(sql,UserService.USER_MEETING), UserActivityBase.class);
	}
	public UserActivityBase getActivityApplyNowByMobile(String mobile) {
		String sql = "select * from user_activity where mobile='"+mobile+"' and type='%s'";
		return bt.queryBean(String.format(sql,UserService.USER_MEETING), UserActivityBase.class);
	}
	final static List<String> idCardList = new ArrayList<String>();
	static{
		idCardList.add("34112619900909201x");
		idCardList.add("131082198810250775"); // 吴泽辰
		idCardList.add("230281198810172612");
		idCardList.add("372324198804200315");
		idCardList.add("142634199105173419"); // 孙鹏举
	}
	public boolean noCheckIdCard(String idCard){
		if(idCardList.contains(idCard)){
			return false;
		}
		return true;
	}
}

